package com.hunttown.mes.manage.controller.exceptions;

import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.shiro.ShiroFilterUtils;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ControllerAdvice
public class ExceptionsHandler {

    /**
     * 自定义异常
     *
     * @param request   request
     * @param response  response
     * @param exception ex
     * @return model
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView allExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) {

        ModelAndView modelAndView = new ModelAndView("/help/error500");
        modelAndView.addObject("errMsg", exception.getMessage());

        try {
            exception.printStackTrace();

            //如果出现这个错误（Request method 'GET' not supported）直接跳转到首页
            if (exception.getMessage().toLowerCase().equals("request method 'get' not supported")) {
                response.sendRedirect("/main-server");
            }

            if (SecurityUtils.getSubject() != null) {
                Subject subject = SecurityUtils.getSubject();
                Session session = subject.getSession();

                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO user = (AnalysisManageDTO) session.getAttribute(KeyConstants.LOGIN_SESSION_ADMIN + pin);

                if (user != null && user.getIsSuper() == 1) {
                    List<String> starckList = new ArrayList<>();
                    for (StackTraceElement element : exception.getStackTrace()) {
                        starckList.add(element.toString());
                    }
                    if (exception.getCause() != null) {
                        starckList.add("");
                        starckList.add("cause by:");
                        for (StackTraceElement element : exception.getCause().getStackTrace()) {
                            starckList.add(element.toString());
                        }
                    }
                    modelAndView.addObject("starcks", starckList);
                    modelAndView.addObject("PIN", pin);
                    modelAndView.addObject("isSuper", 1);
                }
            }

            if (ShiroFilterUtils.isAjax(request)) {
                exception.printStackTrace();
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put("login_status", "500");
                resultMap.put("message", "提示：程序异常(" + exception.getMessage() + ")");
                ShiroFilterUtils.out(response, resultMap);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return modelAndView;
    }
}
